package mr.ali.videoapp.portal.controller;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import mr.ali.videoapp.portal.Bo.LoginBO;
import mr.ali.videoapp.portal.Bo.SubscribeMsgRequest;
import mr.ali.videoapp.portal.model.OpenId;
import mr.ali.videoapp.portal.service.IOpenIdService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Mr-ali
 * @since 2024-08-01
 */
@RestController
@RequestMapping("/portal/openId")
@Slf4j
public class OpenIdController {
    private final String APP_ID = "wx68b7ece486eb3e32";
    private final String APP_SECRET = "d64374fdafaca0a7275dd96b19bf2c68";
    private final String TEMPLATE_ID = "FY_MaeaXFbEG1geQpYAbx27Z8zm4b5BebBOE2qGUeCw"; // 替换为你的模板ID
    @Resource
    IOpenIdService openIdService;

    /**
     * ikran处理登录请求
     *
     * @param loginBO 登录信息对象，包含登录所需参数
     * @return 用户的唯一OpenId
     * @throws IOException 如果请求失败，则抛出IOException异常
     */
    @PostMapping("")
    public OpenId login(@RequestBody LoginBO loginBO) throws IOException {
        // 调用openIdService的getOpenId方法，传入loginBO参数，获取用户的唯一OpenId
        OpenId openId = openIdService.getOpenId(loginBO);
        log.info("获取到的OpenId为:{}", openId);
        // 返回获取到的OpenId
        return openId;
    }

    @GetMapping("/money")
    public void updateMoney(Integer userId, Double money, Boolean close , String channel) {
        openIdService.updateNotMoney(userId, money, close , channel);
    }

    /**
     * ikran01处理登录请求
     *
     * @param loginBO 登录信息对象，包含登录所需参数
     * @return 用户的唯一OpenId
     * @throws IOException 如果请求失败，则抛出IOException异常
     */
    @PostMapping("/ikran")
    public OpenId ikranlogin(@RequestBody LoginBO loginBO) throws IOException {
        // 调用openIdService的getOpenId方法，传入loginBO参数，获取用户的唯一OpenId
        OpenId openId = openIdService.getOpenIdIkran(loginBO);
        log.info("获取到的OpenId为:{}", openId);
        // 返回获取到的OpenId
        return openId;
    }


    /**
     * 获取所有的用户
     */
    @GetMapping("/select")
    public List<OpenId> select() {
        List<OpenId> openIds = openIdService.getAllOpenId();
        return openIds;
    }

    /**
     * 会员身份变成非会员
     */
    @GetMapping("/deleteStatus")
    public Integer deleteOpenId(Integer id, Integer status) {
        Integer rows = openIdService.deleteStatus(id, status);
        return rows;
    }

    /**
     * 非会员身份变成会员
     */
    @GetMapping("/updateStatus")
    public Integer updateOpenId(OpenId openId) {
        Integer rows = openIdService.updateOpenId(openId.getId(), openId.getStatus(), openId.getStatusCreate());
        return rows;
    }


    /**
     * 跳换语言
     */
    @GetMapping("/updateLanguage")
    public Integer updateLanguage(Integer id, Integer language) {
        Integer rows = openIdService.UpLanguage(id, language);
        return rows;
    }

    /**
     * 订阅消息
     */
    @PostMapping("/sendSubscribeMsg")
    public ResponseEntity<String> sendSubscribeMsg(@RequestBody SubscribeMsgRequest request) {
        String accessToken = getAccessToken();
        log.info("accessToken:{}", accessToken);
        log.info("request:{}", request);

        // 构造请求体，填充模板数据
        String requestBody = String.format(
                "{\"touser\":\"%s\", \"template_id\":\"%s\", \"page\":\"pages/index/index\", \"data\": {\"thing1\":{\"value\":\"%s\"},\"time3\":{\"value\":\"%s\"},\"thing4\":{\"value\":\"%s\"},\"time6\":{\"value\":\"%s\"},\"thing7\":{\"value\":\"%s\"}}}",
                request.getUserId(),
                TEMPLATE_ID,
                request.getThing1(),
                request.getTime3(),
                request.getThing4(),
                request.getTime6(),
                request.getThing7()
        );
        log.info("requestBody:{}", requestBody);

        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        // 执行POST请求
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.postForEntity("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, entity, String.class);

        return response;
    }

    /**
     * 订阅消息
     */
    private String getAccessToken() {
        // 使用你的APP_ID和APP_SECRET获取access_token
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APP_ID, APP_SECRET);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

        // 解析响应内容
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode responseJson = objectMapper.readTree(response.getBody());
            String accessToken = responseJson.get("access_token").asText();
            return accessToken; // 返回访问令牌
        } catch (Exception e) {
            e.printStackTrace();
            return null; // 出错时返回 null，实际业务中要做更详细的异常处理
        }
    }


}

